//
//  WCFileGetInfoWindowController.m
//  WabbitCode
//
//  Created by William Towe on 4/3/09.
//  Copyright 2009 Revolution Software. All rights reserved.
//

#import "WCFileGetInfoWindowController.h"
#import "WCProject.h"
#import "WCTextFile.h"
#import "EncodingManager.h"
#import "WCAppController.h"


@implementation WCFileGetInfoWindowController
#pragma mark -
#pragma mark *** Subclass Overrides ***
- (void)dealloc {
	[_file release];
	[super dealloc];
}

- (void)windowDidLoad {
	[super windowDidLoad];
	
	if (!NSIsEmptyRect([[self file] getInfoWindowFrame]))
		[[self window] setFrame:[[self file] getInfoWindowFrame] display:NO];
	
	if ([[self file] isKindOfClass:[WCTextFile class]]) {
		[_encodingPopUpButton setEncoding:([(WCTextFile *)[self file] fileEncoding] == NoStringEncoding)?kWCDefaultFileEncoding:[(WCTextFile *)[self file] fileEncoding] defaultEntry:YES];
	}
	else {
		[_encodingPopUpButton setEnabled:NO];
	}
}

- (NSString *)windowTitleForDocumentDisplayName:(NSString *)displayName {
	if (!_hasSetRepresentedFilename) {
		_hasSetRepresentedFilename = YES;
		[[self window] setRepresentedFilename:@""];
	}
	
	return [NSString stringWithFormat:NSLocalizedString(@"File \"%@\" Info",@"file get info window title"), [[self file] name]];
}

#pragma mark NSWindow Delegate
- (void)windowDidResize:(NSNotification *)note {
	[[self file] setGetInfoWindowFrame:[[note object] frame]];
}

- (void)windowDidMove:(NSNotification *)note {
	[[self file] setGetInfoWindowFrame:[[note object] frame]];
}
#pragma mark NSControl Delegate
- (BOOL)control:(NSControl *)control textShouldEndEditing:(NSText *)fieldEditor {
	return ([[fieldEditor string] length])?YES:NO;
}
#pragma mark -
#pragma mark *** Public Methods ***
+ (WCFileGetInfoWindowController *)getInfoWindowControllerWithFile:(WCFile *)file; {
	return [[[[self class] alloc] initWithFile:file] autorelease];
}

- (id)initWithFile:(WCFile *)file; {
	if (!(self = [super initWithWindowNibName:@"WCFileGetInfoWindow"]))
		return nil;
	
	_file = [file retain];
	
	return self;
}
#pragma mark Accessors
@synthesize file=_file;

@dynamic project;
- (WCProject *)project {
	return (WCProject *)[self document];
}
#pragma mark IBActions
- (IBAction)choosePathAction:(id)sender; {
	NSOpenPanel *panel = [NSOpenPanel openPanel];
	
	[panel beginSheetForDirectory:[[self file] folderPath] file:nil modalForWindow:[self window] modalDelegate:self didEndSelector:@selector(_choosePathOpenPanelDidEnd:code:info:) contextInfo:NULL];
}

- (IBAction)encodingPopUpButtonAction:(id)sender; {
	[(WCTextFile *)[self file] setFileEncoding:([_encodingPopUpButton selectedTag] == NoStringEncoding)?kWCDefaultFileEncoding:[_encodingPopUpButton selectedTag]];
}
#pragma mark -
#pragma mark *** Private Methods ***
- (void)_choosePathOpenPanelDidEnd:(NSOpenPanel *)panel code:(NSInteger)code info:(void *)info {
	if (code != NSOKButton)
		return;
	
	[[self file] setAbsoluteFilePath:[[panel filenames] objectAtIndex:0]];
}
@end
